﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.NET.QuartzConfig
{
    public static class QuartzSetup
    {
        public static IServiceCollection AddQuartzService(this IServiceCollection services)
        {

            services.AddQuartz(q =>
            {
                q.UseMicrosoftDependencyInjectionJobFactory();
                q.AddJobListener<JobListener>();
                q.GetQuartzConfigurator();

            });

            services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

            return services;
        }

        public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, string cronExpression) where T : IJob
        {
            // Use the name of the IJob as the appsettings.json key
            string jobName = typeof(T).Name;

            var configKey = $"Quartz:{jobName}";

            // register the job as before
            var jobKey = new JobKey(jobName);
            quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

            quartz.AddTrigger(opts => opts.ForJob(jobKey).WithIdentity(jobName + "-trigger").WithCronSchedule(cronExpression)); // use the schedule from configuration

        }
    }

    public class JobListener : IJobListener
    {
        public string Name => nameof(JobListener);

        public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            return Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"Job: {context.JobDetail.Key} 即将执行");

            }, cancellationToken);
        }

        public Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            return Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"Job: {context.JobDetail.Key} 被否决执行");

            }, cancellationToken);
        }

        public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
        {
            return Task.Factory.StartNew(() =>
            {
                Console.WriteLine($"Job: {context.JobDetail.Key} 执行完成");

            }, cancellationToken);
        }
    }
}
